import {getNav} from "@/api"
import mainRouter from "@/router/dynamicsRouter";
import routers from "@/router"

function mapToRouter(menus = [], res = []) {
    for (let menu of menus) {
        if (menu.children) {
            mapToRouter(menu.children, res)
        }
        if (menu.menuType === "导航菜单") {
            let item = {
                path: menu.url,
                name: menu.menuId,
                component: () => {
                    return menu.component ? import(`@/views/${menu.component}`) : null
                },
                meta: {
                    title: menu.menuName,
                    isDynamic: true,
                    perm: menu.perm
                }
            }
            res.push(item)
        }
    }
    return res

}

export default {
    state: {
        menuList: []
    },
    mutations: {
        setMenuList(state, data) {
            state.menuList = data

        }
    },
    actions: {
        getMenuList({commit}) {
            return new Promise((resolve, reject) => {
                getNav().then(d => {
                    commit("setMenuList", d.data.menus);
                    let router = mapToRouter(d.data.menus);
                    let r = Object.assign({}, mainRouter)
                    r.children = router
                    routers.addRoutes([r])
                    routers.options.isAddDynamicMenuRoutes = true
                    resolve(d.data.menus)
                }).catch(e => {
                    reject(e)
                })

            })
        },

    }
}
